package com.distribute.captcha;

import java.io.IOException;
import java.time.LocalDateTime;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.distribute.common.Constant;
import com.distribute.common.exception.ValidateCodeException;

/**
 * 校验验证码的过滤器
 * 
 * @author zhailiang
 *
 */
@Component("validateCodeFilter")
public class ValidateCodeFilter extends OncePerRequestFilter {

	@Autowired
	private AuthenticationFailureHandler authenticationFailureHandler;

	
	// 每个请求都走该过滤器，包含资源文件请求
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		// 点击登录按钮请求  Request URL: http://127.0.0.1:83/login
		if (request.getServletPath().equals(Constant.DO_LOGIN_URL)) {
			String code = request.getParameter("code");
			HttpSession session = request.getSession();
			ValidateCode sessionValidateCode = (ValidateCode)session.getAttribute(CodeController.SESSION_IMAGE_CODE);
			if(StringUtils.isBlank(code) 
				|| null == sessionValidateCode
				|| StringUtils.isBlank(sessionValidateCode.getCode())
				|| LocalDateTime.now().isAfter(sessionValidateCode.getExpireTime())
				|| !StringUtils.equals(code, sessionValidateCode.getCode())) {
				ValidateCodeException exception = new ValidateCodeException("验证码错误");
				authenticationFailureHandler.onAuthenticationFailure(request, response, exception );
				return;
			}
		}
		chain.doFilter(request, response);
	}
}
